<template>
    <div class="video-playback-wrapper">
        <!-- header -->
        <div class="timeline-header">
            <div class="header-left">
                <!-- 时间选择器 -->
                <el-time-picker
                    v-model="currentTime"
                    placeholder="选择时间"
                    format="HH:mm:ss"
                    value-format="HH:mm:ss"
                    size="small"
                    @change="handleTimeJump"
                />
                <!-- 跳转按钮 -->
                <el-button 
                    type="primary" 
                    size="small" 
                    @click="handleTimeJump"
                    :disabled="!currentTime"
                >
                    <el-icon><Position /></el-icon>
                    跳转
                </el-button>
            </div>
            
            <!-- 时间轴缩放控制 - 居中显示 -->
            <div class="zoom-controls">
                <el-button 
                    type="info" 
                    size="small"
                    @click="zoomOut"
                    :disabled="initZoomIndex <= 0"
                >
                    <el-icon><Minus /></el-icon>
                </el-button>
                <el-button 
                    type="info" 
                    size="small"
                    @click="zoomIn"
                    :disabled="initZoomIndex >= 10"
                >
                    <el-icon><Plus /></el-icon>
                </el-button>
            </div>
            
            <div class="header-right">
                <!-- 声音禁音按钮 -->
                <el-button 
                    :type="isMuted ? 'danger' : 'default'" 
                    size="small"
                    @click="toggleMute"
                >
                    <el-icon>
                        <Mute v-if="isMuted" />
                        <Microphone v-else />
                    </el-icon>
                    {{ isMuted ? '取消禁音' : '禁音' }}
                </el-button>
                
                <!-- 清屏按钮 -->
                <el-button 
                    type="warning" 
                    size="small"
                    @click="clearScreen"
                >
                    <el-icon><Delete /></el-icon>
                    清屏
                </el-button>
                
                <!-- 暂停播放按钮 -->
                <el-button 
                    :type="isPlaying ? 'warning' : 'success'" 
                    size="small"
                    @click="togglePlayback"
                >
                    <el-icon>
                        <VideoPause v-if="isPlaying" />
                        <VideoPlay v-else />
                    </el-icon>
                    {{ isPlaying ? '暂停' : '播放' }}
                </el-button>
            </div>
        </div>
        
        <div class="video-timeline-container">
            <CustomTimeline 
                ref="timelineRef"
                :startTime="'00:00:00'"
                :endTime="'23:59:59'"
                :currentTime="currentTimeDisplay"
                :zoomLevel="initZoomIndex"
                :timeSegments="timeSegments"
                :deviceList="deviceList"
                :enableDrag="true"
                :enableZoom="false"
                @timeChange="handleTimeChange"
                @zoomChange="handleZoomChange"
            />
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { 
    ElTimePicker, 
    ElButton, 
    ElIcon 
} from 'element-plus'
import {
    Position,
    Mute,
    Microphone,
    Delete,
    VideoPause,
    VideoPlay,
    Plus,
    Minus
} from '@element-plus/icons-vue'
import CustomTimeline from './CustomTimeline.vue'
import { usePlaybackStore } from '@/stores/playback'

// Props定义
interface Props {
    // 选择的日期
    selectedDate?: string
    // 初始缩放级别
    zoomIndex?: number
    // 窗口列表数据
    windowData?: any[]
    // 初始时间
    initialTime?: string | number
    // 是否使用平滑缩放
    smoothZoom?: boolean
    // 选中的摄像头列表
    selectedCameras?: string[]
    // 异步回放时选中的摄像头
    selectedCameraForAsync?: any
    // 播放模式
    playbackMode?: 'sync' | 'async' | null
}

const props = withDefaults(defineProps<Props>(), {
    selectedDate: '',
    zoomIndex: 0, // 使用最小的缩放级别，显示最大的时间范围
    windowData: () => [],
    initialTime: '',
    smoothZoom: false, // 禁用平滑缩放
    selectedCameras: () => [],
    selectedCameraForAsync: null,
    playbackMode: null
})

// 使用playback store
const playbackStore = usePlaybackStore()

// Emits定义
const emit = defineEmits<{
    timeChange: [time: number]
    muteChange: [isMuted: boolean]
    clearScreen: []
    playbackChange: [isPlaying: boolean]
    zoomChange: [zoomIndex: number]
}>()


// CustomTimeline组件引用
const timelineRef = ref()

// Header状态变量
const currentTime = ref('')
const isMuted = ref(false)
// 使用playback store中的isPlaying状态，而不是本地状态
const isPlaying = computed(() => playbackStore.isPlaying)

// 当前时间显示（用于CustomTimeline）
const currentTimeDisplay = computed(() => {
    if (currentTime.value) {
        return currentTime.value
    }
    return '00:00:00'
})

// 时间段数据（用于CustomTimeline）
const timeSegments = computed(() => {
    // 优先使用真实的录像数据
    if (playbackStore.playbackRecords.length > 0) {
        console.log('VideoPlaybackControl: 使用真实录像数据生成时间段:', playbackStore.playbackRecords)
        
        const segments: any[] = []
        const colors = ['#4CAF50', '#2196F3', '#FF9800', '#E91E63', '#9C27B0', '#00BCD4']
        
        // 按设备分组录像记录
        const recordsByCamera = new Map<number, any[]>()
        
        playbackStore.playbackRecords.forEach(record => {
            // 使用channel或ChannelId作为设备ID，因为equId固定为0
            const cameraId = record.channel || record.ChannelId || record.equId || 0
            console.log('VideoPlaybackControl: timeSegments - 处理录像记录:', {
                record,
                cameraId,
                channel: record.channel,
                ChannelId: record.ChannelId,
                equId: record.equId
            })
            if (!recordsByCamera.has(cameraId)) {
                recordsByCamera.set(cameraId, [])
            }
            recordsByCamera.get(cameraId)!.push(record)
        })
        
        // 为每个设备的录像记录生成时间段
        let colorIndex = 0
        recordsByCamera.forEach((records, cameraId) => {
            records.forEach((record, index) => {
                const startTime = new Date(record.startTime).getTime()
                const endTime = new Date(record.endTime).getTime()
                
                segments.push({
                    beginTime: startTime,
                    endTime: endTime,
                    color: colors[colorIndex % colors.length],
                    startRatio: 0.1 + (cameraId * 0.1), // 不同设备在不同高度
                    endRatio: 0.1 + (cameraId * 0.1) + 0.05,
                    label: `设备${cameraId}-录制${index + 1}`,
                    cameraId: cameraId.toString(),
                    recordIndex: record.index
                })
            })
            colorIndex++
        })
        
        return segments
    }
    
    // 如果没有录像数据，使用windowData作为备选
    if (props.windowData && props.windowData.length > 0) {
        const segments: any[] = []
        props.windowData.forEach((window: any) => {
            if (window.timeSegments) {
                segments.push(...window.timeSegments)
            }
        })
        return segments
    }
    
    return []
})

// 设备列表
const deviceList = computed(() => {
    // 如果有录像记录，从录像记录中提取设备信息
    if (playbackStore.playbackRecords && playbackStore.playbackRecords.length > 0) {
    
    // 从录像记录中提取设备信息
    const deviceMap = new Map()
    
    playbackStore.playbackRecords.forEach((record: any) => {
        // 使用ChannelId来匹配设备，因为EquId固定为0
        const deviceId = record.channel || record.ChannelId || record.equId || record.cameraId || 'unknown'
        
        if (!deviceMap.has(deviceId)) {
            // 尝试从cameraList中找到对应的设备信息
            let deviceName = `设备${deviceId}`
            let deviceInfo = null
            
            // 在所有文件夹的摄像头列表中查找匹配的设备
            for (const [, cameras] of playbackStore.folderCameraMap) {
                deviceInfo = cameras.find(camera => 
                    camera.equId === deviceId || 
                    camera.id === deviceId || 
                    camera.subEquId === deviceId ||
                    camera.id.toString() === deviceId.toString()
                )
                if (deviceInfo) {
                    break
                }
            }
            
            // 如果在folderCameraMap中没找到，尝试在cameraList中查找
            if (!deviceInfo) {
                deviceInfo = playbackStore.cameraList.find(camera => 
                    camera.equId === deviceId || 
                    camera.id === deviceId || 
                    camera.subEquId === deviceId ||
                    camera.id.toString() === deviceId.toString()
                )
            }
            
            // 如果找到设备信息，使用设备的真实名称
            if (deviceInfo) {
                deviceName = deviceInfo.name || `设备${deviceId}`
            }
            
            // 为每个设备分配一个颜色
            const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd']
            const colorIndex = deviceMap.size % colors.length
            
            deviceMap.set(deviceId, {
                id: deviceId.toString(),
                name: deviceName,
                color: colors[colorIndex]
            })
        }
    })
    
    const result = Array.from(deviceMap.values())
    return result
    } else {
        // 没有录像记录时，根据选中的摄像头生成设备列表
        if (props.selectedCameras && props.selectedCameras.length > 0) {
            const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd']
            const selectedDevices = []
            
            // 从所有文件夹的摄像头中查找选中的摄像头
            for (const [, cameras] of playbackStore.folderCameraMap) {
                for (const camera of cameras) {
                    // 尝试多种ID匹配方式
                    const cameraIdStr = camera.id.toString()
                    const deviceIdStr = `device_${camera.id}`
                    
                    if (props.selectedCameras.includes(cameraIdStr) || 
                        props.selectedCameras.includes(deviceIdStr)) {
                        selectedDevices.push({
                            id: camera.id.toString(),
                            name: camera.name || `摄像头${camera.id}`,
                            color: colors[selectedDevices.length % colors.length]
                        })
                    }
                }
            }
            
            return selectedDevices
        }
        
        // 如果没有选中的摄像头，返回空数组
        return []
    }
})

// 初始缩放级别
const initZoomIndex = ref(props.zoomIndex)

// 监听selectedCameras变化，强制重新计算deviceList
watch(() => props.selectedCameras, () => {
    // 强制重新计算deviceList
    nextTick(() => {
        // deviceList会自动重新计算
    })
}, { deep: true })



// 处理时间变化事件
const handleTimeChange = async (time: string) => {
    currentTime.value = time
    
    // 如果有选中的日期，构建完整的日期时间字符串用于seek
    if (props.selectedDate) {
        const fullDateTime = `${props.selectedDate} ${time}`
        console.log('执行seek到时间:', fullDateTime)
        
        // 调用store的seekToPosition方法，传入目标时间
        await playbackStore.seekToPosition(0, fullDateTime)
    }
    
    // 将时间转换为时间戳发送给父组件
    const [hours, minutes, seconds] = time.split(':').map(Number)
    const timestamp = new Date().setHours(hours, minutes, seconds, 0)
    emit('timeChange', timestamp)
}

// 处理缩放变化事件
const handleZoomChange = (level: number) => {
    initZoomIndex.value = level
    emit('zoomChange', level)
}


// Header相关方法
// 时间跳转
const handleTimeJump = async () => {
    if (currentTime.value) {
        // 如果有选中的日期，构建完整的日期时间字符串用于seek
        if (props.selectedDate) {
            const fullDateTime = `${props.selectedDate} ${currentTime.value}`
            console.log('执行时间跳转seek到:', fullDateTime)
            
            // 调用store的seekToPosition方法，传入目标时间
            await playbackStore.seekToPosition(0, fullDateTime)
        }
        
        // 重新绘制时间轴
        if (timelineRef.value && timelineRef.value.redraw) {
            timelineRef.value.redraw()
        }
    }
}

// 切换禁音状态
const toggleMute = () => {
    isMuted.value = !isMuted.value
    emit('muteChange', isMuted.value)
}

// 清屏
const clearScreen = () => {
    emit('clearScreen')
}

// 切换播放状态
const togglePlayback = async () => {
    if (isPlaying.value) {
        // 当前正在播放，执行暂停
        await playbackStore.pausePlayback()
    } else {
        // 当前已暂停，执行播放
        await playbackStore.resumePlayback()
    }
    // 发送播放状态变化事件给父组件
    emit('playbackChange', isPlaying.value)
}

// 缩放控制方法
const zoomIn = () => {
    if (initZoomIndex.value < 5) {
        initZoomIndex.value++
        emit('zoomChange', initZoomIndex.value)
        // 重新绘制时间轴
        nextTick(() => {
            if (timelineRef.value && timelineRef.value.redraw) {
                timelineRef.value.redraw()
            }
        })
    }
}

const zoomOut = () => {
    if (initZoomIndex.value > 0) {
        initZoomIndex.value--
        emit('zoomChange', initZoomIndex.value)
        // 重新绘制时间轴
        nextTick(() => {
            if (timelineRef.value && timelineRef.value.redraw) {
                timelineRef.value.redraw()
            }
        })
    }
}

// 监听props变化，更新缩放级别
watch(() => props.zoomIndex, (newValue) => {
    initZoomIndex.value = newValue
})

// 监听selectedDate变化，重新绘制时间轴
watch(() => props.selectedDate, () => {
    // 当日期变化时，重新绘制时间轴
    nextTick(() => {
        if (timelineRef.value && timelineRef.value.redraw) {
            timelineRef.value.redraw()
        }
    })
})

// 监听缩放级别变化，重新绘制时间轴
watch(() => initZoomIndex.value, () => {
    // 当缩放级别变化时，重新绘制时间轴
    nextTick(() => {
        if (timelineRef.value && timelineRef.value.redraw) {
            timelineRef.value.redraw()
        }
    })
})

// 监听录像数据变化，重新绘制时间轴
watch(() => playbackStore.playbackRecords, () => {
    console.log('VideoPlaybackControl: 录像数据变化，重新绘制时间轴')
    nextTick(() => {
        if (timelineRef.value && timelineRef.value.redraw) {
            timelineRef.value.redraw()
        }
    })
}, { deep: true })

// 监听异步回放选中摄像头变化，重新绘制时间轴
watch(() => props.selectedCameraForAsync, (newCamera, oldCamera) => {
    if (props.playbackMode === 'async' && newCamera && newCamera !== oldCamera) {
        console.log('VideoPlaybackControl: 异步回放选中摄像头变化，重新绘制时间轴', newCamera)
        nextTick(() => {
            if (timelineRef.value && timelineRef.value.redraw) {
                timelineRef.value.redraw()
            }
        })
    }
}, { deep: true })

// 导出方法供父组件使用
defineExpose({
    redraw: () => {
        if (timelineRef.value && timelineRef.value.redraw) {
            timelineRef.value.redraw()
        }
    }
})
</script>
<style lang="scss" scoped>
.video-playback-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    
    .timeline-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background-color: #2a2a2a;
        border-bottom: 1px solid #3a3a3a;
        position: relative;
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .zoom-controls {
            display: flex;
            align-items: center;
            gap: 4px;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }
    }
    
    .video-timeline-container {
        flex: 1;
        background-color: #1a1a1a;
        border-radius: 0 0 4px 4px;
        overflow: hidden;
        
        :deep(.timeLineContainer) {
            background-color: #1a1a1a;
            height: 100%;
            
            .canvas {
                background-color: #2a2a2a;
            }
            
            .windowList {
                background-color: #1a1a1a;
            }
        }
    }
}
</style>